package com.boot.unity.api.common.page;

import com.google.common.collect.Maps;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Map;

public class PageTableArgumentResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        Class<?> cla = parameter.getParameterType();
        return cla.isAssignableFrom(PageTableRequest.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);

        PageTableRequest tableRequest = new PageTableRequest();
        Map<String,String[]> param = request.getParameterMap();

        Integer currentPage = 1;
        Integer pageSize = 10;
        // 第几页信息
        if(param.containsKey("currentPage")){
            currentPage = Integer.parseInt(request.getParameter("currentPage"));
        }

        // 若currentPage<1,重新赋值1
        if(currentPage < 1){
            currentPage = 1;
        }

        if(param.containsKey("pageSize")){
            pageSize = Integer.parseInt(request.getParameter("pageSize"));
        }

        // 设置分页偏移量offset
        tableRequest.setOffset((currentPage-1)*pageSize);
        // 设置分页数量limit
        tableRequest.setLimit(pageSize);
        // 参数暂时设置为空
        Map<String, Object> map = Maps.newHashMap();
        tableRequest.setParams(map);

        param.forEach((k, v) -> {
            if(!k.equals("currentPage") && !k.equals("pageSize") && !k.equals("total") && !k.equals("background")){
                if(v.length ==1){
                    map.put(k,v[0]);
                }else {
                    map.put(k,Arrays.asList(v));
                }
            }
        });
        return tableRequest;
    }
}
